package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.admin.dtos.AdChannelDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmChannelDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmChannelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 查询所有频道
     *
     * @return
     */
    @Override
    public ResponseResult findAll() {

        //查询启用的频道
        List<WmChannel> wmChannels = wmChannelMapper.selectList(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getStatus, true));
        return ResponseResult.okResult(wmChannels);
    }

    /**
     * 频道列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmChannelDto dto) {
        //检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //分页参数检查
        dto.checkParam();
        //分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        //条件构造器
        LambdaQueryWrapper<WmChannel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //按照频道名称模糊查询
        lambdaQueryWrapper.like(WmChannel::getName, dto.getName());
        //可以按照状态进行精确查找（1：启用   true           0：禁用   false）
        //lambdaQueryWrapper.eq(WmChannel::getStatus,true);
        //按照创建时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmChannel::getCreatedTime);
        wmChannelMapper.selectPage(page, lambdaQueryWrapper);
        //返回结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 删除频道
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delChannel(Integer id) {
        //1.检查参数
        if (id == null || id == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询数据
        WmChannel wmChannel = wmChannelMapper.selectById(id);
        if (wmChannel == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (!wmChannel.getStatus()) {
            //只有禁用的频道才能删除
            wmChannelMapper.deleteById(id);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(501, "当前频道未被禁用,不能删除");
    }

    /**
     * 新增频道
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveChannel(AdChannelDto dto) {
        //检查参数
        if (dto == null || StringUtils.isBlank(dto.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //频道名词不能重复
        WmChannel wmChannel = wmChannelMapper.selectOne(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getName, dto.getName()));
        if (wmChannel != null) {
            //频道名称已存在
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //初始化数据
        wmChannel = new WmChannel();
        BeanUtils.copyProperties(dto, wmChannel);
        wmChannel.setIsDefault(true);
        wmChannel.setCreatedTime(new Date());
        //保存数据
        wmChannelMapper.insert(wmChannel);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 修改频道
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateChannel(AdChannelDto dto) {
        //检查参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //数据是否存在

        WmChannel wmChannel = wmChannelMapper.selectById(dto.getId());
        if (wmChannel == null) {
            //数据不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //如果频道被引用则不能禁用
        if (dto.getStatus() != null && !dto.getStatus()) {
            LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getId());
            List<WmNews> wmNews = wmNewsMapper.selectList(lambdaQueryWrapper);
            if (wmNews != null && wmNews.size() > 0) {
                return ResponseResult.errorResult(501, "当前频道被引用不能禁用");
            }
        }
        BeanUtils.copyProperties(dto, wmChannel);
        wmChannel.setCreatedTime(new Date());

        //保存数据
        wmChannelMapper.updateById(wmChannel);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
